package toy.keli.picmap;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import toy.keli.picmap.adapter.ImageListAdapter;
import toy.keli.picmap.model.def;
import toy.keli.picmap.model.event;
import toy.keli.picmap.model.pic;
import toy.keli.picmap.model.system;
import toy.keli.picmap.model.types.PhotoItem;

public class PicOne {
    public int index;
    Dialog dialog;
    ImageView image;
    String dialogShowType="pic"; //attr
    float scale=1;
    float picLeft=0;
    float picTop=0;
    def zoomPoints=new def();
    Matrix matrix = new Matrix();
    Matrix currentMaritx = new Matrix();
    boolean hpFlage=false;
    PicActivity act;

    public PicOne(PicActivity act){
        this.act=act;
        hpFlage=(act.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
    }

    //图片全屏幕展示 https://blog.csdn.net/ykx_1448488568/article/details/86238620
    public void show(int i){
        index=i;
        zoomPoints.empyt();
        dialogShowType = "pic";   picLeft=picTop=0;
        if(dialog==null) dialogInit();
        View box=dialog.findViewById(R.id.pic_box);
        if(box==null){
            picInitEvent();
        }
        try {
            pic picModel=getPic();
            String fileName=picModel.file;
            FileInputStream fis= new FileInputStream(new File(fileName));//文件输入流
//            Drawable drawable = BitmapDrawable.createFromStream(fis, null);
//            image.setImageDrawable(drawable);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 1;
            opts.inJustDecodeBounds = false;
            Bitmap bitMap = BitmapFactory.decodeStream(fis,null,opts);
            float w=bitMap.getWidth(),h=bitMap.getHeight(),left=0,top=0;
            //角度
            int degree= pic.getRotateDegree(fileName);
            boolean exchangeWH=(degree==90||degree==270);

            float winHeight=act.winHeight ,winWidth= act.winWidth;

            if(exchangeWH) {
                float tmp=w;
                w=h;
                h=tmp;
            }
            //缩放比例 横屏按照高度来缩放，竖屏按照宽度来缩放
            float scale=(hpFlage)? winHeight / h : winWidth / w;
            w*=scale; h*=scale;
            //计算 角度旋转之后的偏移
            switch (degree) {
                case 90:
                    left=w;
                    break;
                case 180:
                    left=w;
                    top=h;
                    break;
                case 270:
                    top=h;
                    break;
                case 0:

            }
            //边框留白
            if(!hpFlage){  //竖屏扁长
                //if(h<w)
                top += (winHeight - h) / 2;
            }else if(hpFlage && h>w){    //横屏高挑
                left+=(winWidth-w)/2;
            }
            Log.d("kdebug", "top:"+top+",left:"+left+",hpFlage:"+hpFlage+",h:"+h+",w:"+w);
            matrix.reset();
            matrix.postRotate(degree);      //旋转
            matrix.postScale(scale, scale); //缩放
            matrix.postTranslate(left,top); //偏移

            image.setImageBitmap(bitMap);
            image.setImageMatrix(matrix);
            //Android之最简单的ImageView加边框方法 https://www.cnblogs.com/exmyth/p/4450170.html
            picMoreSet();
            currentMaritx.set(matrix);
            dialog.show();
            scale=1;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    void picMoreSet(){
        ImageView redioButton=dialog.findViewById(R.id.more_select);
        TextView shareButtion= dialog.findViewById(R.id.more_share);

        ((TextView)dialog.findViewById(R.id.more_date)).setText(getPic().getStringTime()+" "+(index+1));

        if(act.mAdapter==null || act.mAdapter.getItemCount()==0){
            redioButton.setVisibility(View.GONE);
            shareButtion.setVisibility(View.VISIBLE);
            if(act.mAdapter==null) {
                act.mAdapter = new ImageListAdapter();
                PhotoItem img = get();
                act.mAdapter.setSelectedImage(img);
            }
            return;
        }
        int count=act.mAdapter.getSelectedImages().size();
        if(count>0) {
            dialog.findViewById(R.id.pic_more).setVisibility(View.VISIBLE);
            shareButtion.setVisibility(View.VISIBLE);
            redioButton.setVisibility(View.VISIBLE);
            redioButton.setBackgroundResource(get(index).isSelected() ? R.drawable.ic_selected: R.drawable.ic_no_select);
            shareButtion.setText("分享("+count+")");
        }else{
            shareButtion.setVisibility(View.GONE);
            redioButton.setVisibility(View.GONE);
        }
    }
    void dialogInit(){
        PicActivity listself = act;
        dialog = new Dialog(act, R.style.FullActivity);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            //单张图片关闭
            @Override
            public void onDismiss(DialogInterface dialog) {
//                    if(dialogShowType.equals("attr"))  {
//                        dialogShowType="pic";
//                        onShopPic(index);
//                    }
//                    else
                if(listself.mAdapter==null || listself.mAdapter.getItemCount()==0) listself.finish();
            }
        });

        picInitEvent();
    }

    void picInitEvent(){
        dialog.setContentView(R.layout.pic_show);
//        image=new ImageView(act);
        image=dialog.findViewById(R.id.pic_box);
        //对话框Dialog背景透明功能示例 https://www.jb51.net/article/118845.htm  ， setbackgroundcolor()方法的使用 http://www.voidcn.com/article/p-mjosphqh-wt.html
        image.setBackgroundColor(Color.parseColor("#000000"));
        image.setScaleType(ImageView.ScaleType.MATRIX);

        //宽高
        //image.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        View more=dialog.findViewById(R.id.pic_more);
        //标题单击不要有反映
        more.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                pic picNow = new pic(get().getPath());
                picNow.attrs((data)->{
                    picInitAttr(data);
                });
                return true;
            }
        });
        more.findViewById(R.id.more_go_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.hide();
            }
        });
        //横评和竖屏切换    https://blog.csdn.net/m0_37711172/article/details/80496663
        more.findViewById(R.id.more_hp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hpFlage=!hpFlage;
                if(hpFlage)
                    act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏
                else
                    act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
                more.setVisibility(View.GONE);
                //show(index);
            }
        });
        //选择按钮
        more.findViewById(R.id.more_select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                act.mAdapter.setEnableSelect(index);
                show();
            }
        });
        more.findViewById(R.id.more_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                act.sharePic(true);
            }
        });
        more.findViewById(R.id.more_share).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                act.sharePic(false);
                return true;
            }
        });

        //imageView设置图片
        event.bind(image,(t)->{
            switch (t) {
                case LEFT:
                    if (scale == 1 && act.mAdapter!=null && act.mAdapter.itemEvents!=null)
                        act.mAdapter.itemEvents.onChange(true);
                    break;
                case DOWN:
                    Log.d("kdebug", "down");
                    if(scale == 1 && dialogShowType.equals("pic")) {
                        pic picNow = new pic(get().getPath());
                        picNow.attrs((data)->{
                            picInitAttr(data);
                        });
                    }
                    break;
                case UP:
                    Log.d("kdebug", "up");
                case RIGHT:
                    if (scale == 1 && act.mAdapter!=null && act.mAdapter.itemEvents!=null)
                        act.mAdapter.itemEvents.onChange(false);
                    break;
                case CLICK:
                    //显示浮层信息
                    Log.d("kdebug", "click");
                    if(scale<1)
                    {
                        picLeft=picTop=0;
                        zoomPoints.empyt();
                        scale= event.zoomScale=1;
                        matrix.set(currentMaritx);
                        matrix.postScale(scale, scale);
                        image.setImageMatrix(matrix);
                        return ;
                    }
                    more.setVisibility(more.getVisibility()==View.VISIBLE? View.GONE: View.VISIBLE);
                    dialog.getContext().setTheme(more.getVisibility()==View.VISIBLE ?  R.style.AppTheme_PopupOverlay: R.style.FullActivity);
                    break;
                case LONGCLICK:
                    Log.d("kdebug", "longclick");
                    if(scale==1 && picLeft+picTop==0) {
                        act.mAdapter.setEnableSelect(index);
                        show();
                    }
                    //进入选择状态
                    break;
                case DRAG:  //移动图片   https://www.jianshu.com/p/5e30db034596
                    float dx = event.end.x - event.begin.x;
                    float dy = event.end.y - event.begin.y;
                    float max=Math.max(Math.abs(dx),Math.abs(dy));
                    //实现上下左右延迟移动
                    if (scale == 1 ) {
                        int ignoreNum = 5;
                        boolean isXChange = (max == Math.abs(dx));
                        if (max < ignoreNum) return;
                        if (dx != max || dy != max) ignoreNum = 0 - ignoreNum;
                        if (isXChange) {
                            dx += ignoreNum;
                            dy = 0;
                        } else {
                            dy += ignoreNum;
                            dx = 0;
                        }
                    }
                    matrix.postTranslate(dx, dy);
                    image.setImageMatrix(matrix);
                    picLeft -= dx;
                    picTop -= dy;
                    break;
                case DCLICK:
                    //固定放大
//                    int[] sArray={1,3,5};
//                    int now=(int) event.zoomScale;
//                    int i=utilArray.indexOf(sArray,now);
//                    event.zoomScale=(i==-1 || i==sArray.length-1 || event.zoomScale-now>0) ? 1: sArray[i+1];
                    event.zoomScale = event.zoomScale !=1  ? 1 : 4;
                    if(event.zoomScale==1){
                        picLeft=picTop=0;
                        zoomPoints.empyt();
                    }
                case ZOOM:
                    //放大和缩小图片  http://blog.sina.com.cn/s/blog_6816889701014o2f.html  , https://www.cnblogs.com/zhangming-blog/articles/5356073.html
                    scale = Math.max(0.1f, Math.min(50, event.zoomScale));
                    float x = event.begin.x, y = event.begin.y;
                    //计算连续缩放信息 重新给x,y赋值
                    String key=(int)x + "," + (int)y;
                    float[] a = (float[]) zoomPoints.get(key).source();
                    int size=zoomPoints.size();
                    if (a == null){
                        if (size > 1) {
                            float x0 = x, y0 = y;
                            x = (picLeft + x) / scale;
                            y = (picTop + y) / scale;
                        }
                        Log.d("kdebug",""+(int)x+","+(int)y);
                        zoomPoints.set(key,new float[]{x,y});
                    }else{
                        if (size > 1) {
                            picLeft = a[0] * scale - a[0];
                            picTop = a[1] * scale - a[1];
                        }
                        x=a[0];
                        y=a[1];
                    }
                    if(size<2){
                        picLeft = event.begin.x * scale - event.begin.x;
                        picTop = event.begin.y * scale - event.begin.y;
                    }

                    matrix.set(currentMaritx);
                    matrix.postScale(scale, scale, x,y);
                    image.setImageMatrix(matrix);
                    break;
                case ZOOM_OVER:
                    //松开事件
                    if(scale==1 && !matrix.equals(currentMaritx))
                    {
                        matrix.set(currentMaritx);
                        matrix.postScale(1,1);
                        image.setImageMatrix(matrix);
                    }
                    break;
            }
        });
    }
    //显示图片属性列表
    void picInitAttr(def data){
        // 简单列表  https://www.jb51.net/article/135202.htm
        dialog.setTitle("图片详情");
        dialog.setContentView(R.layout.pic_view);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(dialog.getContext(), android.R.layout.simple_list_item_1, data.toStrings(true));
        ListView attrs= dialog.findViewById(R.id.picView);
        attrs.setAdapter(adapter);
        final int[] scrollCount = {1,0};
        dialog.findViewById(R.id.go_back_attr).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show(index);
            }
        });
        dialog.findViewById(R.id.del_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                act.ConfirmDialog("删除确认","确定要删除这个图片嘛？",()->{
                   getPic().remove();
                   act.msg("删除成功");
                });
            }
        });
        attrs.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (attrs.getLastVisiblePosition() == (attrs.getCount() - 1)) {
                            Log.d("kdebug","buttom");
                            scrollCount[1]++;
                            scrollCount[0]=0;
                        }
                        // 判断滚动到顶部
                        else if(attrs.getFirstVisiblePosition() == 0){
                            scrollCount[0]++;
                            scrollCount[1]=0;
                            Log.d("kdebug","top");
                        }else return;
                        if(scrollCount[0]+scrollCount[1]<2) return;
                        show(index);
                        break;
                }
            }
        });
        attrs.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                String text = adapter.getItem(position);
                system.copy(act,text);
                system.msg(act,"内容复制成功");
                return false;
            }
        });
        attrs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = adapter.getItem(position);
                if(text.startsWith("关键字")){
                    act.prompt("修改关键字",text.substring(5),(tex)->{
                       if(!text.equals(tex)) {
                           pic p = getPic();
                           p.name=tex;
                           p.save();
                           act.msg("修改成功！");
                           data.set("关键字",tex);
                           picInitAttr(data);
                       }
                    });
                }
            }
        });
        dialogShowType = "attr";
        return;
    }

    public void show() {
        show(index);
    }

    public boolean isShowing() {
        return dialog!=null && dialog.isShowing();
    }

    public PhotoItem get(){
        return get(index);
    }
    public PhotoItem get(int i){
        return act.mDatas.get(i);
    }
    pic getPic(){
        return new pic(get().getPath());
    }
}
